<?php

namespace Apps\AppApi\Method\Question;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\QuestionAnswer;
use Apps\Common\Models\QuestionAnswerFollow;
use PhalconPlus\Api\Common\ResultStatus;


/**
 * 问题答案点赞
 * @package Apps\AppApi\Method\Question
 */
class AnswerFollow extends BaseMethod
{
    /**
     * @var int
     */
    private $success = 0;
    /**
     * @var string
     */

    public function run()
    {
        /**
         * 验证用户权限
         */
        if(false == $this->verifyUserAuth()){
            return false;
        }
        $user = $this->getUserAuth();

        /**
         * 获取关注次数
         */
        $answerId = intval($this->getDataItem('answer_id',0));

        if($answerId <= 0) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, "答案ID必须大于0.");
        }
        $follow = QuestionAnswerFollow::count([
            "conditions"=>"user_id = :uid: AND answer_id = :aid: ",
            "bind" => [
                'uid' => $user->userId,
                'aid' => $answerId,
            ],
        ]);

        /**
         * 有权限且未关注则执行关注
         */
        if($follow == 0) {
            /**
            * 记录关注动作
            */
            $qaf = new QuestionAnswerFollow();
            $qaf->user_id = $user->userId;
            $qaf->answer_id = $answerId;
            if($qaf->save()) {
//                QuestionAnswer::updateFollows($answerId); // 不要以前的
                QuestionAnswer::setSupportCount($answerId, 1);

                $this->success = 1;
            } else {
                return $this->databaseErrorLog($qaf);
            }
        } else {
            $this->success = 2;
        }

        $this->setResult(["success" => $this->success]);
    }

}